// 兑换记录页面逻辑
Page({
  data: {
    id: null,
    detail: null,
    trackingSteps: [],
    allHistory: [],
    filteredHistory: [],
    currentFilter: 'all',
    totalExchanges: 0,
    shippedExchanges: 0,
    pendingExchanges: 0,
    completedExchanges: 0,
    pageSize: 10,
    hasMore: true,
    loading: false,
    error: null,
    lastRefreshTime: 0 // 新增：记录上次刷新时间
  },

  onLoad() {
    this.loadExchangeHistory();
  },

  onShow() {
    // 页面显示时刷新数据，确保状态是最新的
    try {
      const app = getApp();
      if (app && app.globalData && app.globalData.needRefreshHistory) {
        console.log('检测到全局刷新标志，刷新兑换历史');
        app.globalData.needRefreshHistory = false;
        this.loadExchangeHistory();
      } else {
        // 如果没有全局刷新标志，检查是否需要刷新
        // 避免频繁刷新，只在必要时刷新
        const now = Date.now();
        const lastRefreshTime = this.data.lastRefreshTime || 0;
        if (now - lastRefreshTime > 5000) { // 5秒内不重复刷新
          console.log('常规刷新兑换历史');
          this.loadExchangeHistory();
        }
      }
    } catch (error) {
      console.error('检查全局刷新标志失败:', error);
      // 出错时也刷新数据
      this.loadExchangeHistory();
    }
  },

  // 加载兑换记录
  loadExchangeHistory() {
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    
    if (!userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用后端接口获取用户兑换订单历史列表（多表联查）
    wx.request({
      url: 'http://localhost:8080/point/order/history/' + userInfo.id,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        page: this.data.page,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        wx.hideLoading();
        console.log('兑换历史API返回数据:', res.data);
        
        if (res.data.code === 200) {
          const historyList = res.data.data || [];
          // 转换数据格式，根据实际API返回的字段名和嵌套结构
          const allHistory = historyList.map(item => ({
            id: item.id,
            title: item.goodsName || (item.mallGoods ? item.mallGoods.name : ''),
            imageUrl: this.getFullImageUrl(item.mallGoods ? item.mallGoods.coverImg : ''),
            points: item.point || 0,
            time: item.createTime || '',
            status: this.getStatusText(item.status),
            orderSn: item.orderSn || '',
            trackingNumber: item.logistics ? item.logistics.expressNo : '',
            expressCompany: item.logistics ? item.logistics.expressCompany : '',
            goodsId: item.goodsId,
            addressId: item.addressId,
            mallGoods: item.mallGoods,
            logistics: item.logistics
          }));

          console.log('转换后的兑换历史:', allHistory);

          // 计算统计数据
          const totalExchanges = allHistory.length;
          const shippedExchanges = allHistory.filter(item => item.status === 'shipped').length;
          const pendingExchanges = allHistory.filter(item => item.status === 'pending').length;
          const completedExchanges = allHistory.filter(item => item.status === 'completed').length;

          this.setData({
            allHistory: allHistory,
            filteredHistory: allHistory,
            totalExchanges,
            shippedExchanges,
            pendingExchanges,
            completedExchanges,
            hasMore: historyList.length >= this.data.pageSize,
            lastRefreshTime: Date.now() // 更新刷新时间
          });

          this.filterHistory();
        } else {
          wx.showToast({
            title: res.data.msg || '获取兑换历史失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取兑换历史失败', err);
        wx.showToast({
          title: '获取兑换历史失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取完整的图片URL
  getFullImageUrl(imagePath) {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    return 'https://gzq123.oss-cn-beijing.aliyuncs.com/' + imagePath;
  },

  // 获取状态文本
  getStatusText(status) {
    switch (status) {
      case 0:
        return 'pending';
      case 1:
        return 'shipped';
      case 2:
        return 'completed';
      default:
        return 'pending';
    }
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
    this.filterHistory();
  },

  // 筛选兑换记录
  filterHistory() {
    let filtered = [];
    
    switch (this.data.currentFilter) {
      case 'shipped':
        filtered = this.data.allHistory.filter(item => item.status === 'shipped');
        break;
      case 'pending':
        filtered = this.data.allHistory.filter(item => item.status === 'pending');
        break;
      case 'completed':
        filtered = this.data.allHistory.filter(item => item.status === 'completed');
        break;
      default:
        filtered = this.data.allHistory;
        break;
    }
    
    this.setData({
      filteredHistory: filtered
    });
  },

  // 根据状态筛选
  filterByStatus(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      currentFilter: status
    });
    this.filterHistory();
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/my/pages/exchange-detail/exchange-detail?id=${id}`
    });
  },

  // 复制快递单号
  copyTracking(e) {
    const trackingNumber = e.currentTarget.dataset.number;
    if (trackingNumber && trackingNumber.trim()) {
      wx.setClipboardData({
        data: trackingNumber,
        success: () => {
          wx.showToast({
            title: '单号已复制',
            icon: 'success'
          });
        }
      });
    } else {
      wx.showToast({
        title: '暂无快递单号',
        icon: 'none'
      });
    }
  },

  // 复制订单号
  copyOrderNumber(e) {
    const orderSn = e.currentTarget.dataset.number;
    if (orderSn && orderSn.trim()) {
      wx.setClipboardData({
        data: orderSn,
        success: () => {
          wx.showToast({
            title: '订单号已复制',
            icon: 'success'
          });
        }
      });
    }
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      return;
    }

    this.setData({
      page: this.data.page + 1
    });

    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用后端接口加载更多数据
    wx.request({
      url: 'http://localhost:8080/point/order/history/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        page: this.data.page,
        pageSize: this.data.pageSize,
        userId: userInfo.id
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          const newHistoryList = res.data.data || [];
          const formattedNewHistory = newHistoryList.map(item => ({
            id: item.id,
            title: item.goodsName || (item.mallGoods ? item.mallGoods.name : ''),
            imageUrl: this.getFullImageUrl(item.mallGoods ? item.mallGoods.coverImg : ''),
            points: item.point || 0,
            time: item.createTime || '',
            status: this.getStatusText(item.status),
            orderSn: item.orderSn || '',
            trackingNumber: item.logistics ? item.logistics.expressNo : '',
            expressCompany: item.logistics ? item.logistics.expressCompany : '',
            goodsId: item.goodsId,
            addressId: item.addressId,
            mallGoods: item.mallGoods,
            logistics: item.logistics
          }));

          const allHistory = [...this.data.allHistory, ...formattedNewHistory];
          this.setData({
            allHistory: allHistory,
            page: this.data.page,
            hasMore: newHistoryList.length >= this.data.pageSize
          });
          this.filterHistory();
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('加载更多失败', err);
        wx.showToast({
          title: '加载更多失败',
          icon: 'none'
        });
      }
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '兑换记录',
      path: '/my/pages/exchange-history/exchange-history'
    };
  },

  // 更新兑换历史（被其他页面调用）
  updateExchangeHistory() {
    console.log('收到状态更新通知，刷新兑换历史');
    this.loadExchangeHistory();
  }
}); 